define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    require("./selfSupply");
    var nums = $(".add-content").find("div.form-group").length;
    var picNums = $(".add-industry").find("div.form-group").length;
    var type = $("#edited").val();
    var f = true;

    if(picNums>1){
        $(".add-industry").find("button.del").removeClass("hide");
    }

    if(type == "1"){
        $(".set-usename").addClass("hide");
    }

    $("#add_more").on("click",function(){
        var data={},_html;
            nums++;
            data.num = nums;
        _html = template("js_more_temp",data);
        $(_html).insertBefore($(this).parent());
    })

    $("#add_industry").on("click",function(){
         var data={},_html;nums = $(".add-industry").find("div.form-group").length;
             data.num = nums +1;
            var lastBox = $(".add-industry").find("div.form-group:last");
            _html = template("js_industry_temp",data);
            $(_html).insertBefore($(this).parent());
            
            data.size = $(".add-industry").find("div.form-group").length;
            if($(".add-industry").find("div.form-group").length > 1){
                $(".add-industry").find("button.del").removeClass("hide");
            }
    })

    $(document).on("click","button.del",function(){
        $(this).closest("div.form-group").remove();
        if($(".add-industry").find("div.form-group").length <= 1){
            $(".add-industry").find("button.del").addClass("hide");
        }
        prizeSet();
    });

    var prizeSet = function(){
         $(".add-industry .form-group").each(function(i){
            var num = i+1;
            var name = $(this).find("[data-required-box='input']").data("name");
            $(this).find("label.control-label").html('行业资质'+num+'：');
            $(this).find("[data-required-box='input']").attr({"name":""+name+"["+num+"]"});
         })
    }

    var $method1 = $('[data-toggle="method1"]',$(".form-validate"));
    if ($method1.length > 0) {
        var $method_hidden = $("#method"),
            fog = false,msg,
            $confirm = $method1.data('confirm');
        $method1.on("click", function() {
            var $this = $(this),
                method_val = $this.data("method");
            var done = function() {
                $method_hidden.val(method_val);
                // $this.button("loading");
                $method1.closest('form').submit();
            }
            $confirm && config.msg.msgbox.confirm($method1.data('msg') || config.lang.confirmCloseOrder, function(result) {
                if (result) {
                    done();
                }
            });
            if ($method1.closest('form').valid()) {
                var nums=[];
                $("[data-required-box='input']").each(function(i){
                    if($(this).val() == ""){
                        msg = $(this).data("msg");
                        fog = true;
                    }else{
                        nums.push($(this));
                    }
                })

                if(nums.length == $("[data-required-box='input']").length){
                    fog = false;
                }

                if(fog){
                    config.msg.error("请上传{0}".format(msg));
                    return;
                }
                
                if (window.formValided) {
                     (!$confirm && method.validKindEditor()) && done();
                };
               
            };
        })
    };


    $(".switch_account").length && $(".switch_account").on("change",function(){
        if($(this).data("val")){
            $("div.js_password").addClass("hide");
        }else{
            $("div.js_password").removeClass("hide");
        }
    });

    if($(".switch_account:checked").data("val")){
        $("div.js_password").addClass("hide");
    }else{
        $("div.js_password").removeClass("hide");
    }

    //基本信息
    $(document).on("change",".js_change_bank",function(){
        var box = $(this).find("option:selected").data("box");
        $("div.js_hide").addClass("hide");
        $("."+box).removeClass("hide");
    })


    //类目选择
    $(".js_all").click(function(){
        if($(this).prop("checked")){
            $(this).closest("td").next("td").find("input").attr("checked",true);
        }else{
            $(this).closest("td").next("td").find("input").attr("checked",false);
        }
    })
    var $js_classes_select=$(".js_classes_select");
    $js_classes_select.length && (function(){
        var val=$js_classes_select.val();
         classes(val);
    })();
    $(document).on("click",".js_classes_select",function(){
         classes($(this).val());
    });
    function classes(val){
        $(".js_classes_show").addClass("hide").find("input").addClass('wizard-ignore').prop("disabled",true);
        $(".js_classes_show_"+val).removeClass("hide").find("input").removeClass('wizard-ignore').prop("disabled",false);
    }
    $(document).on("click",".js_account_type",function(){
        accoutSwitch($(this));
    });
    var $js_account_type=$(".js_account_type:checked");
    $js_account_type.length && (function(){
        accoutSwitch($js_account_type);
    })();
    function accoutSwitch(obj){
        var $this=obj,$js_register_select=$(".js_register_select"),type=$this.data("type"),
        $js_submit_register_select=$(".js_submit_register_select");
        $js_register_select.addClass("hide").find("input").prop("disabled",true);
        $js_submit_register_select.addClass("hide");
        $(".js_"+type).removeClass("hide").find("input").prop("disabled",false);
        $(".js_submit_"+type).removeClass("hide");
    }
    $(document).on("click",".js_submit_register",function(){
        var $this=$(this),$form=$this.closest("form"),$name=$("#register_uersnam"),msg=$this.data("msg");
        if($form.valid()){
            config.msg.msgbox.confirm(msg+ $name.val(), function(result) {
                if (result) {
                    $form.submit();
                }
            });
        }
        /*var $this=$(this),$form=$this.closest('form'),msg=$this.data("msg"),
        path=$this.data("path"),$js_error_account_pwd=$(".js_error_account_pwd"),
        $p=$js_error_account_pwd.closest('.form-group'),$name=$("#register_uersnam"),
        $pwd=$("#register_password"),name=$name.val(),$js_error_account_pwd=$(".js_error_account_pwd"),
        $js_investgames_modal=$(".js_investgames_modal"),sid=$("#supplierId",$form).val();
        if($form.valid()){
            $this.prop("disabled",true);
            $.ajax(path, {
                type: "post",
                data: {account:name,password:$pwd.val(),id:sid,type:$(".js_account_type:checked",$form).val()},
                dataType: "json"
            }).done(function(data) {
                if(data.status==1){
                    $js_error_account_pwd.addClass('hide');
                    $("#investgames_lists").html(template("investgames_template",data));
                    $js_investgames_modal.modal("show");
               }else if(data.status==2){
                     $js_error_account_pwd.html(data.message).removeClass("hide");
               }else{
                    config.msg.msgbox.confirm(msg+name, function(result) {
                        if (result) {
                            $form.submit();
                        }
                    });
                    $js_error_account_pwd.addClass('hide');
               }
               $this.prop("disabled",false);
            }).fail(function() {
                $this.prop("disabled",false);
                config.msg.info(config.lang.exception)
            });
        }*/
        
    });
    window.multyInvestGames=function(data){
        var $js_error_account_pwd=$(".js_error_account_pwd"),$form=$("#add_account_form"),
        $js_investgames_modal=$(".js_investgames_modal"),id=$js_investgames_modal.data("id");
        if(data.status==1){
            $js_error_account_pwd.addClass('hide');
             data.id=id;
            $("#investgames_lists").html(template("investgames_template", data));
            $js_investgames_modal.modal("show");
        }else{
            $js_error_account_pwd.html(data.message).removeClass("hide");
        }
        
    }
    window.clearId=function(){
       $(".js_aid_id").val("");
       var $modal=$(".js_investgames_modal");
       $(".js_investgames_save",$modal).button('reset');
    }
    
    $(document).on("click",".js_submit_noregister",function(){
        var $this=$(this),$form=$this.closest("form"),$name=$("#noregister_uersnam"),msg=$this.data("msg");
        if($form.valid()){
            config.msg.msgbox.confirm(msg+ $name.val(), function(result) {
                if (result) {
                    $form.submit();
                }
            });
        }
    });
    $(document).on("click",".js_investgames_list",function(){
        var $this=$(this),falg=$this.hasClass("active");
        $(".js_investgames_list").removeClass("active");
        if(falg){
            $this.removeClass("active");
        }else{
           $this.addClass("active");  
        }
    });
    $(document).on("click",".js_investgames_save",function(){
        var $this=$(this),$form=$this.closest('form'),$add_account_form=$("#add_account_form"),
        $js_aid_id=$(".js_aid_id"),$on=$(".js_investgames_list.active"),id=$on.data("id");
        if($on.length){
            $js_aid_id.val(id);
            $add_account_form.submit();
            $this.button("loading");
        }else{
            config.msg.info("请选择公众号");
        }
    });
    
    if ($('.js_commision:checked').length > 0) {
        if ($('.js_commision:checked').val() == 1) {
            $('.js_output').hide();
        }
    } else {
        $('.js_output').hide();
    }
    $(document).on('click', '.js_commision', function() {
        var $type = $(this).val();
        if ($type == 0) {
            $('.js_output').show();
        } else {
            $('.js_output').hide();
        }
    });


    //新增品牌
    $('.js_firs').live("click",function(){
        if($(this).find('input').prop("checked")){
            $(this).next("td").find("input").attr("checked",true);
        }else{
            $(this).next("td").find("input").attr("checked",false);
        }
    })
    $('.js_sec input').live("click",function(){
        if($(this).prop("checked")){
            $(this).parents('td').prev("td").find("input").attr("checked",true);
        }
        else
        {
            var oInp=$(this).parents('td').find('input');
            var nNum=oInp.size(),n=0;
            var $this=$(this);
            oInp.each(function(){
                if(!$(this).prop('checked'))
                {
                    n++;
                    if(n==nNum)
                    {
                        $this.parents('td').prev("td").find("input").attr('checked',false)
                    }
                }
            })
        }
    });
    


    //添加品牌
    window.updateLabel=function(data){

        var $selObj=$(".js_add_label");
        var $select2_4 = $('[data-toggle="select2_4"]', document);
        var new_arr=[];
        var flag=true;
        $('[data-toggle="select2_4"] option').each(function(){
            new_arr.push($(this).attr('value'));
        });
        $select2_4.empty();
        $("ul.select2-selection__rendered .select2-selection__choice").each(function(index){
            var old_val=$(this).text().substring(1);
            $select2_4.append("<option value="+new_arr[index]+" selected>"+old_val+"</option>");
            if(old_val==data.value)
            {
                flag=false;
                config.msg.info("已添加该品牌");
            }
        });
        if(flag)
        {
            $select2_4.append("<option value="+data.key+" selected>"+data.value+"</option>");

            var text = $(".js_modal .init").val();
            var dataTmp ={};
            dataTmp.id= data.key;
            dataTmp.text = text;
            console.log(dataTmp.text);
            if(window.add_label){
                var $html = template("trademark_temp",dataTmp);
                $($html).appendTo($(".js_trademark"));
            }
            arr1.push(text);
            arr1_id.push(data.key.toString());
        }

        function formatRepo(repo) {
            if (repo.loading) return repo.text;
            var markup = '<li>' + repo.value + '</li>';
            return markup;
        }

        function formatRepoSelection(repo) {
            return repo.value || repo.text;
        }
        
        $select2_4.length > 0 && require.async(['select2_4'], function() {
            $select2_4.each(function() {
                var t = $(this),
                    n = {},
                    c = t.data('maxcount'),
                    o = t.data('chang'),
                    r = t.data('remote') || t.attr('href'),
                    pid = t.data("pid"),
                    required_msg = t.data("msgRequired") || t.data("placeholder");
                c && (n.maximumSelectionSize = c);
                if (o) {
                    switch (o) {
                        case "submit":
                            {
                                t.on("change", function(e) {
                                    t.closest("form ").submit();
                                })
                            }
                    }
                };
                if (r) {
                    if (pid != undefined) {
                        r = r.format(pid);
                    }
                    t.select2({
                        ajax: {
                            url: r,
                            dataType: 'json',
                            delay: 500,
                            data: function(params) {
                                return {
                                    q: params.term, // search term
                                    page: params.page || 1
                                };
                            },
                            processResults: function(data, params) {
                                if (config.issucceed(data)) {
                                    params.page = params.page || 1;
                                    if (params.page == 1) {
                                        data.items.unshift({
                                            "id": "js_select2_4placeholder",
                                            "value": t.data("placeholder")
                                        });
                                    }

                                    return {
                                        results: data.items,
                                        pagination: {
                                            more: (params.page * data.page_num) < data.total_count
                                        }
                                    };
                                } else {
                                    config.msg.error(data.message || config.lang.sendError);
                                }
                            },
                            cache: true
                        },
                        escapeMarkup: function(markup) {
                            return markup;
                        },
                        minimumInputLength: 0,
                        templateResult: formatRepo,
                        templateSelection: formatRepoSelection
                    });
                } else {
                    
                    t.select2(n)
                }
                t.change(function() {
                    var $this = $(this);
                    if ($this.val() == "js_select2_4placeholder") {
                        $this.find("option:selected").attr("value", "");
                    }
                });

            })
        });

       
    }
    //主营类目
    $("#next").click(function(){
        if($("#secondStep").is(":visible")==true){
            var check = [];
            $(".js_classes_show input:checked").each(function(i,n){
                check.push(n.value);
            })
            var val = {};
            val.select = $(".js_classes_select").val();
            val.checkbox = check;
            $.ajax({
                type:"post",
                url:window.path,
                data: val,
                dataType:"json"
            }).done(function(d){
                if(d.status == 0){
                    $(".js_category").html("");
                    var $html = template("category_temp",d);
                    $($html).appendTo($(".js_category"));
                }
            }).fail(function() {
                window.msg.info("网络异常请重试")
            });
        }
    })

    //新增品牌
    var text1 ,text2;
    var arr1 = [];
    var arr2 = [];
    var arr3 = [];
    var arr1_id = [];
    var arr2_id = [];
    var arr3_id = [];

    $(document).ready(function(){
        arr1_id = $('.js_add_label').val();
        if(arr1_id == null){
            arr1_id = [];
        }
        text1 = $(".select2-selection__choice").text();
        arr1 = text1.split("×");
        arr1.splice(0,1);
    })

    $(document).on('change','.js_add_label',function(){
        arr2_id = $('.js_add_label').val();
        text2 = $(".select2-selection__choice").text();
        arr2 = text2.split("×");
        arr2.splice(0,1);
        arr3 = [];
        arr3_id = [];

        if(arr2.length > arr1.length){
            for (var i=0; i<arr2.length;i++){
                if(arr1.indexOf(arr2[i])== -1){
                    arr3.push(arr2[i]);
                }
            }

            for (var i=0; i<arr2_id.length;i++){
                if(arr1_id.indexOf(arr2_id[i])== -1){
                    arr3_id.push(arr2_id[i]);
                }
            }

            arr1 = arr1.concat(arr3);
            arr1_id = arr1_id.concat(arr3_id);
            var data ={};
            data.text= arr3[0];
            data.id=arr3_id[0];

            if(window.add_label){
                var $html = template("trademark_temp",data);
                $($html).appendTo($(".js_trademark"));
            }

        }else if(arr2.length < arr1.length){
            for(var i=0; i<arr1.length;i++){
                if(arr2.indexOf(arr1[i])== -1){
                    arr3.push(arr1[i]);
                    arr1.splice(i,1);
                }
            }
            $(".js_title").each(function(){
                if($(this).html() == arr3[0]){
                    $(this).closest(".trademark_list").remove();
                }
            })
        }
    })

    $(document).on('click','.js_putin',function(){
        var sVal=$('.js_hideval').val();
        var $this=$(this);
        if($this.closest("form").valid() && sVal)
        {
            $this.submit();
        }
        if(!sVal)
        {
            $('.js_tipnone').removeClass('hide');
        }
    });

    $(document).on("callback",'[data-toggle="selectimg"]',function(data){
        if(data)
        {
            $('.js_tipnone').addClass('hide');
        }
    });
    var $js_self_support_select=$(".js_self_support_select:checked");
    $js_self_support_select.length && (function(){
        selfSupport($js_self_support_select);
    })();

    $(document).on("click",".js_self_support_select",function(){
        selfSupport($(this));
    });
    function selfSupport($obj){
        var type=$obj.data("type");
        $(".js_self_support_div").addClass("hide").find("input").prop("disabled",true);
        $(".js_self_support_select_"+type).removeClass("hide").find("input").prop("disabled",false);
    }
    
    //推单设置控制
    storeType();
    $(document).on('click', '.js_storeType', function(){
        storeType();
    })
    function storeType(){
        var $js_storeType = $(".js_storeType:checked");
        switch ($js_storeType.val()){ 
        case "4" : $('.pushSetting').removeClass('hide');
        break; 
        case "5" : $('.pushSetting').removeClass('hide');
        break; 
        case "6" : $('.pushSetting').removeClass('hide');
        break; 
        case "7" : $('.pushSetting').removeClass('hide');
        break; 
        default : $('.pushSetting').addClass('hide');
        break; 
        } 
    }

    if(window.ports_data){
        $(document).on('change', '.js_change_city', function(){
            var $city = $(this);
            var cityName = $(this).find('option:selected').text();
            var $bill = [];
            $city.closest('.col-sm-11').find('.js_customs_port_bill:checked').each(function(){ 
                if($(this).attr("checked")){
                    $bill.push($(this).next('span').text());
                }
            })
            var billType = $(this).closest('.col-sm-11').find('.js_customs_port_bill:checked');
            $city.closest('div.col-sm-11').next().find("span.js_City").html(cityName);
            $city.closest('div.col-sm-11').next().addClass("hide").prop("disabled",true);
            ports_data1($city, cityName, $bill, billType);
        })
        $(document).on('click', '.js_customs_port_bill', function(){
            var $city = $(this).closest('.col-sm-11').find('.js_change_city');
            var cityName = $(this).closest('.col-sm-11').find('.js_change_city option:selected').text();
            var $bill = $(this);
            var billType = $(this).next('span').text();
            ports_data2($city, cityName, $bill, billType);
        })
    }
    function ports_data1(obj1, obj2, obj3, obj4){
        if(obj2=='' || obj2=='请选择'){
                obj1.closest('div.col-sm-11').next().addClass("hide").prop("disabled",true);
            }else{
                var eValue=eval('window.ports_data.'+obj2);
                for(var item in eValue){
                    if(eValue[item] == 'true'){
                        for(var obj in eValue){
                            if(obj==item){
                                for(var jValue in obj3){
                                    if(obj3[jValue]==obj){
                                        obj1.closest('div.col-sm-11').next().find("span.js_Bill").html(obj);
                                        obj1.closest('div.col-sm-11').next().removeClass("hide").prop("disabled",false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
    }
    function ports_data2(obj1, obj2, obj3, obj4){
        if(obj2==''){
                obj1.closest('div.col-sm-11').next().addClass("hide").prop("disabled",true);
            }else{
                for(var item in window.ports_data){
                    if(item==obj2){  //item 表示Json串中的属性，如'name' 
                        var jValue=window.ports_data[item];//key所对应的value
                        var eValue=eval('jValue.'+obj4);
                        if(obj3.prop("checked")){
                            if(eValue=="true"){
                                obj3.closest('div.col-sm-11').next().find("span.js_Bill").html(obj4);
                                obj3.closest('div.col-sm-11').next().removeClass("hide").prop("disabled",false);
                            }
                        }else{
                            if(eValue=="true"){
                                obj3.closest('div.col-sm-11').next().addClass("hide").prop("disabled",true);
                            }
                        }
                    }  
                }
            }
    }
    
});